package com.husd.framework.util;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class DownloadFileUtil {

    /**
     * 下载文件
     *
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "", method = RequestMethod.GET)
    //@ApiOperation(value = "下载文件 需要传2个参数 urlStr: 文件地址 fileName:文件名称")
    public boolean download(HttpServletResponse response, String urlStr, String fileName) throws IOException {
       // log.info("downloading url:{}, fileName:{} ", urlStr, fileName);
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), "ISO-8859-1"));
        this.download(response.getOutputStream(), urlStr);
        return true;

    }

    public void download(OutputStream out, String urlPath) {
        InputStream in = null;
        try {
            URL url = new URL("http:" + urlPath);
            URLConnection conn = url.openConnection();

            // 读取文件内容。
            in = conn.getInputStream();
            byte[] buffer = new byte[1024];
            int lenght = 0;
            while ((lenght = in.read(buffer)) != -1) {
                out.write(buffer, 0, lenght);
            }
        } catch (Exception e) {
            //log.error("download exception", e);
            throw new RuntimeException("");
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    //IGNORE
                   // log.warn("close outputStream.", e);
                }

            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    //IGNORE
                    //log.warn("close inputStream.", e);
                }
            }
        }
    }
}
